<!--
 * @Author: your name
 * @Date: 2020-12-02 11:14:01
 * @LastEditTime: 2021-04-08 21:15:16
 * @LastEditors: Please set LastEditors
 * @Description: 组装计算表
 * @FilePath: \cang-chu-guan-li-xi-tong\src\components\common\AssemblyCalculationSheet.vue
-->

<template>
  <div>
    <a-button type="primary" @click="showModal"> 组装计算表 </a-button>
    <a-modal
      title="组装计算表"
      @cancel="handleCancel"
      :visible="visible"
      width="70%"
    >
      <template slot="footer">
        <a-button @click="Reset"> 重置 </a-button>
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button type="primary" @click="handleOk"> 确定 </a-button>
      </template>

      <a-table
        style="margin-top: 20px"
        :columns="columns"
        :data-source="dataSource"
        bordered
        size="middle"
        :scroll="{ x: 3000 }"
        :pagination="false"
      >
        <!-- 原材料仓库名称 -->
        <span slot="partsdepotName" slot-scope="text, record">
          <a-select
            v-model="record.partsdepotName"
            showSearch
            style="width: 100%"
            @change="getPartsDepotId(record.key)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotNo"
              :value="item.depotId + '|' + item.depotNo + '|' + item.depotName"
            >
              {{ item.depotNo }} {{ item.depotName }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 原材料名称 -->
        <span
          slot="partsInventoryName"
          slot-scope="text, record"
          v-if="record.key != '合计'"
        >
          <a-select
            v-model="record.partsInventoryName"
            showSearch
            style="width: 100%"
            @change="setPriceAndRate(record.key)"
          >
            <a-select-option
              v-for="item in partsInventoryInformationList"
              :key="item.partsInventoryId"
              :value="
                item.partsInventoryNo +
                '|' +
                item.partsInventoryName +
                '|' +
                item.key
              "
              >{{ item.partsInventoryNo }}
              {{ item.partsInventoryName }}</a-select-option
            >
          </a-select>
        </span>

        <!-- 加工材料仓库名称 -->
        <span slot="packagedepotName" slot-scope="text, record">
          <a-select
            v-model="record.packagedepotName"
            showSearch
            style="width: 100%"
            @change="getPackageDepotId(record.key)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotNo"
              :value="item.depotId + '|' + item.depotNo + '|' + item.depotName"
            >
              {{ item.depotNo }} {{ item.depotName }}
            </a-select-option>
          </a-select>
        </span>

        <span
          slot="processNumber"
          slot-scope="text, record"
          v-if="record.key != '合计'"
        >
          <a-input-number
            v-model="record.processNumber"
            @blur="Compute(record.key)"
          >
          </a-input-number>
        </span>
        <span slot="options" slot-scope="text, record">
          <a v-if="record.key != '合计'" @click="Cancle(record.key)"> 取消 </a>
        </span>

        <!-- 删除 -->
      </a-table>

      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
    </a-modal>
  </div>
</template>
<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  {
    title: "原材料（出库）",
    children: [
      {
        title: "仓库名称",
        dataIndex: "partsdepotName",
        key: "partsdepotName",
        align: "center",
        width: 300,

        scopedSlots: { customRender: "partsdepotName" },
      },
      {
        title: "原材料名称",
        dataIndex: "partsInventoryName",
        key: "partsInventoryName",
        scopedSlots: { customRender: "partsInventoryName" },
        width: 500,
        align: "center",
      },
      {
        title: "实有数量",
        dataIndex: "actualQuantity",
        key: "actualQuantity",
        align: "center",
      },

      {
        title: "加工数量",
        dataIndex: "partsInventoryNumber",
        key: "partsInventoryNumber",
        align: "center",
      },
      {
        title: "单价",
        dataIndex: "partsInventoryPrice",
        key: "partsInventoryPrice",
        align: "center",
      },
      {
        title: "金额",
        dataIndex: "partsInventoryMoney",
        key: "partsInventoryMoney",
        align: "center",
      },
    ],
  },
  {
    title: "加工材料（入库）",
    children: [
      {
        title: "仓库名称",
        dataIndex: "packagedepotName",
        key: "packagedepotName",
        align: "center",
        width: 300,
        scopedSlots: { customRender: "packagedepotName" },
      },
      {
        title: "加工材料名称",
        dataIndex: "packageInventoryName",
        key: "packageInventoryName",
        align: "center",
      },
      {
        title: "加工数量",
        dataIndex: "packageInventoryNumber",
        key: "packageInventoryNumber",
        align: "center",
      },
      {
        title: "单价",
        dataIndex: "packageInventoryPrice",
        key: "packageInventoryPrice",
        align: "center",
      },
      {
        title: "金额",
        dataIndex: "packageInventoryMoney",
        key: "packageInventoryMoney",
        align: "center",
      },
    ],
  },
  {
    title: "加工费",
    children: [
      {
        title: "数量（T）",
        dataIndex: "processNumber",
        key: "processNumber",
        align: "center",
        scopedSlots: { customRender: "processNumber" },
      },
      {
        title: "单价",
        dataIndex: "processingUnitPrice",
        key: "processingUnitPrice",
        align: "center",
      },
      {
        title: "金额",
        dataIndex: "processMoney",
        key: "processMoney",
        align: "center",
      },
      {
        title: "损耗率",
        dataIndex: "lossRate",
        key: "lossRate",
        align: "center",
      },
      {
        title: "比例",
        dataIndex: "ratio",
        key: "ratio",
        align: "center",
      },
      {
        title: "损耗数量",
        dataIndex: "processRateNumber",
        key: "processRateNumber",
        align: "center",
      },
      {
        title: "扣除金额",
        dataIndex: "processRateMoney",
        key: "processRateMoney",
        align: "center",
      },
      {
        title: "合计金额",
        dataIndex: "processTotalMoney",
        key: "processTotalMoney",
        align: "center",
      },
    ],
  },

  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
  },
];

export default {
  data() {
    return {
      Form: {
        supplier: "",
      },
      // 供应商列表
      SupplierList: [],

      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      //
      dataSource: [],
      columns,

      tmp: true,

      visible: false,

      partsInventoryInformationList: [],
      storageList: [],
    };
  },
  mounted() {
    this.getSupplierInfo(); // 获取供应商信息
    this.getPartsInventoryInformationList(); // 获取成套件
    this.fillOrder();
    this.getApplyStorage();
  },
  //
  methods: {
    getPackageDepotId(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      let array = target.packagedepotName.split("|");
      target.packagedepotId = array[0]; // 仓库id
      target.packagedepotcode = array[1]; // 仓库名称
      target.packagedepotName = array[2]; // 仓库名称
    },
    getPartsDepotId(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      let array = target.partsdepotName.split("|");
      target.partsdepotId = array[0]; // 仓库id
      target.partsdepotcode = array[1]; // 仓库名称
      target.partsdepotName = array[2]; // 仓库名称
    },

    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 获取实有数量
    async getActualQuantity(data) {
      return new Promise((resolve) => {
        comHttp.getTotalGoods(data).then((res) => {
          console.log("存货数量", res);
          resolve(res.result.balance);
        });
      });
    },

    // 设置价格和损耗率
    async setPriceAndRate(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];

      let array = target.partsInventoryName.split("|");

      for (let i = 0; i < this.partsInventoryInformationList.length; i++) {
        if (
          this.partsInventoryInformationList[i].partsInventoryNo ==
          parseInt(array[0])
        ) {
          target.partsInventoryId = this.partsInventoryInformationList[
            i
          ].partsInventoryId; // 成套件Id
          target.partsInventoryNo = this.partsInventoryInformationList[
            i
          ].partsInventoryNo; // 成套件No
          // 成套件名称
          target.partsInventoryName = this.partsInventoryInformationList[
            i
          ].partsInventoryName; // 成套件名称
          target.partsInventoryStandardModel = this.partsInventoryInformationList[
            i
          ].partsInventoryStandardModel; // 成套件规格
          target.partsInventoryUnit = this.partsInventoryInformationList[
            i
          ].partsInventoryUnit; // 成套件单位

          // 配件
          target.packageInventoryId = this.partsInventoryInformationList[
            i
          ].packageInventoryId; // 配件Id
          target.packageInventoryNo = this.partsInventoryInformationList[
            i
          ].packageInventoryNo; // 配件No
          target.packageInventoryName = this.partsInventoryInformationList[
            i
          ].packageInventoryName; // 配件名稱

          target.packageInventoryStandardModel = this.partsInventoryInformationList[
            i
          ].packageInventoryStandardModel; // 配件规格型号
          target.packageInventoryUnit = this.partsInventoryInformationList[
            i
          ].packageInventoryUnit; // 配件单位
          target.processingUnitPrice = this.partsInventoryInformationList[
            i
          ].processingUnitPrice.toFixed(4); // 单价
          target.lossRate = this.partsInventoryInformationList[i].lossRate; // 损耗率

          target.ratio = this.partsInventoryInformationList[i].ratio; // 比例

          console.log(this.partsInventoryInformationList[i].partsInventoryName);
        }
      }

      // 根据仓库来获取相应的实有数量信息

      let ActualData = {
        depotId: target.partsdepotId,
        inventoryId: target.partsInventoryId,
      };

      target.actualQuantity = await this.getActualQuantity(ActualData);

      console.log(target);
    },

    // 填入组装单
    fillOrder() {
      this.dataSource = [];
      // console.log("", this.Form.price);
      for (let i = 0; i < 1; i++) {
        let data = {
          key: i + 1,

          // 成套件
          partsdepotName: "",
          partsdepotcode: "",
          partsdepotId: "",

          actualQuantity: 0,

          partsInventoryId: "",
          partsInventoryNo: "",
          partsInventoryName: "",
          partsInventoryStandardModel: "",
          partsInventoryUnit: "",
          partsInventoryNumber: "",
          partsInventoryPrice: "",
          partsInventoryMoney: "",

          // 配件
          packagedepotName: "",
          packagedepotcode: "",
          packagedepotId: "",

          packageInventoryId: "",
          packageInventoryNo: "",
          packageInventoryName: "",
          packageInventoryStandardModel: "",
          packageInventoryUnit: "",
          packageInventoryPrice: "",
          packageInventoryMoney: "",
          packageInventoryNumber: "",

          processNumber: 0,
          processingUnitPrice: "", // 单价
          lossRate: "", // 损耗率
          ratio: "",
          processMoney: "",
          processRateNumber: "",
          processRateMoney: "",
          processTotalMoney: "",
        };
        this.dataSource.push(data);
      }
      this.calculateSum();

      this.tmp = false;
    },

    // 计算总和
    calculateSum() {
      // let sum = {
      //   key: "合计",
      // };
      // this.dataSource.push(sum);
    },

    // 添加一个新的元素
    newMember() {
      // 插入元素
      let data = {
        key: this.dataSource.length + 1,
        isNew: true,

        //  配件
        partsdepotName: "",
        partsdepotcode: "",
        partsdepotId: "",

        actualQuantity: 0,

        partsInventoryId: "",
        partsInventoryNo: "",
        partsInventoryName: "",
        partsInventoryStandardModel: "",
        partsInventoryUnit: "",
        partsInventoryNumber: "",
        partsInventoryPrice: "",
        partsInventoryMoney: "",

        // 成套件
        packagedepotName: "",
        packagedepotcode: "",
        packagedepotId: "",

        packageInventoryId: "",
        packageInventoryNo: "",
        packageInventoryName: "",
        packageInventoryStandardModel: "",
        packageInventoryUnit: "",
        packageInventoryPrice: "",
        packageInventoryMoney: "",
        packageInventoryNumber: "",

        processNumber: 0,
        processingUnitPrice: "", // 单价
        lossRate: "", // 损耗率
        ratio: "",
        processMoney: "",
        processRateNumber: "",
        processRateMoney: "",
        processTotalMoney: "",
      };

      this.dataSource.push(data);

      //
      // this.calculateSum();
    },

    // 重置表单
    Reset() {
      this.dataSource = [];
      this.fillOrder();
    },
    // 删除
    Cancle(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      console.log(target);
      if (target.key == "合计") {
        this.$message.error("合计不能删除");
      } else if (this.dataSource.length == 2) {
        this.$message.error("至少保留一行");
      } else {
        this.dataSource.splice(key, 1);
        this.dataSource.splice(key - 1, 1);
        this.calculateSum();
      }
      console.log(key);
    },

    // 完成的函数
    showModal() {
      this.visible = true;
    },
    // 提交函数,这里的作用是,把计算表中的数据传递到父组件里去
    handleOk() {
      // let AllMoney = 0;
      // for (let i = 0; i < this.dataSource.length; i++) {
      //   AllMoney = AllMoney + this.dataSource[i].processTotalMoney;
      // }
      // console.log("合计金额", AllMoney);

      let checkTag = false;

      for (let i = 0; i < this.dataSource.length; i++) {
        if (
          this.dataSource[i].partsdepotName == "" ||
          this.dataSource[i].partsInventoryName == "" ||
          this.dataSource[i].packagedepotName == ""
        ) {
          checkTag = true;
        }
      }

      if (checkTag) {
        this.$message.error("仓库信息或物品信息请填写完整");
      } else {
        // 准备提交和对提交数据进行验证

        let tag = true;

        for (let i = 0; i < this.dataSource.length; i++) {
          if (
            this.dataSource[i].partsInventoryNumber >
            this.dataSource[i].actualQuantity
          ) {
            tag = false;
          }
        }

        if (tag) {
          this.$emit("send-data", this.dataSource);
          this.Reset();
          this.visible = false;
        } else {
          this.$message.error("加工数量大于实有库存数量,请重新填写");
        }
      }
    },
    // 取消按钮
    handleCancel() {
      this.Reset();
      this.visible = false;
    },

    // 获取供应商信息
    getSupplierInfo() {
      comHttp.getSupplierInfo().then((res) => {
        console.log("所有的供应商信息::::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].id,
            suppilerName: res.result[i].suppilerName,
          };

          this.SupplierList.push(data);
        }
      });
    },
    // 计算
    Compute(key) {
      let target = this.dataSource.filter((item) => item.key === key)[0];
      console.log(target);

      // 加工金额 =  加工数量 * 加工单价
      target.processMoney = (
        target.processNumber * target.processingUnitPrice
      ).toFixed(4);
      // 损耗数量 = 损耗率 * 数量
      target.processRateNumber = target.processNumber * target.lossRate;
      // 扣除金额 = 金额 * 损耗率
      target.processRateMoney = (target.processMoney * target.lossRate).toFixed(
        4
      );
      // 合计金额 = 金额 - 扣除金额
      target.processTotalMoney = (
        target.processMoney - target.processRateMoney
      ).toFixed(4);
      // 原材料数量 = 数量 * 比例
      target.partsInventoryNumber = target.processNumber * target.ratio;
      // 加工材料数量 = 数量- 损耗数量
      target.packageInventoryNumber =
        target.processNumber - target.processRateNumber;
    },
    // 获取成套件信息列表
    getPartsInventoryInformationList() {
      this.partsInventoryInformationList = [];
      comHttp.getAllPackageList().then((res) => {
        console.log("所有的成套件", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            key: i + 1,
            // ------- 成套件
            partsInventoryId: res.result.list[i].partsInventoryInformationId, // 成套件Id
            partsInventoryNo: res.result.list[i].partsInventoryNo, // 成套件No
            // 成套件名称
            partsInventoryName:
              res.result.list[i].partsInventoryInformationId_dictText, // 成套件名称
            partsInventoryStandardModel:
              res.result.list[i].partsSpecificationsModel, // 成套件规格型号
            partsInventoryUnit: res.result.list[i].partsUnit, // 成套件名称

            // 配件
            packageInventoryId:
              res.result.list[i].packageInventoryInformationId, // 配件Id
            packageInventoryNo: res.result.list[i].packageInventoryNo, // 配件No
            packageInventoryName:
              res.result.list[i].packageInventoryInformationId_dictText, // 配件名稱

            packageInventoryStandardModel:
              res.result.list[i].specificationsModel, // 配件规格型号
            packageInventoryUnit: res.result.list[i].unit, // 配件单位
            processingUnitPrice: res.result.list[i].processingUnitPrice, // 单价
            lossRate: res.result.list[i].lossRate, // 损耗率
            ratio: res.result.list[i].ratio, // 损耗率
          };
          this.partsInventoryInformationList.push(data);
        }
      });
    },
    //
  },
};
</script>
